package cn.hloger.spider.common.bean; /**
 * TODO
 *
 * @Description TODO
 * @author huanglong
 * @data 2024/7/18
 */

import cn.hloger.spider.utils.DateUtils;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import org.springframework.http.HttpStatus;

/**
 * @author long
 * @version 1.0
 * @description: TODO
 * @date 2024/7/18 15:12
 */
@Data
@AllArgsConstructor
@ToString
@JsonFormat
public class ApiResponse<T> {
    private String msg;
    private int code;
    private T data;
    private String time;


    public static <T> ApiResponse<T> success(T data) {
        ApiResponse<T> apiResponse = getByHttpStatus(HttpStatus.OK);
        apiResponse.setData(data);
        return apiResponse;
    }

    public static <T> ApiResponse<T> fail(String msg) {
        ApiResponse<T> apiResponse = getByHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        apiResponse.setMsg(msg);
        return apiResponse;
    }

    public static ApiResponse<String> fail(Exception e) {
        ApiResponse<String> apiResponse = getByHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        apiResponse.setData(e.getLocalizedMessage());
        return apiResponse;
    }

    public static <T> ApiResponse<T> getByHttpStatus(HttpStatus httpStatus) {
        return new ApiResponse<>(httpStatus.getReasonPhrase(), httpStatus.value(), null, DateUtils.getDateNew());
    }
}
